﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.WebTesting;
using System.ComponentModel;
using System.Text.RegularExpressions;

namespace QA.TFS.Rules.Extraction
{
    public class QueryStringParameters : ExtractionRule
    {

        public string RegExp { get; set; }

        [DefaultValue("HIDDEN")]
        public string Preffix { get; set; }

        [DefaultValue(1)]
        public int MatchIndexAsLabels { get; set; }

        [DefaultValue(0)]
        public int MatchIndexAsValues { get; set; }

        public string Labels { get; set; }

        [DefaultValue(false)]
        public bool StopOnFails { get; set; }

        public override void Extract(object sender, ExtractionEventArgs e)
        {
            if (e.Response.HtmlDocument != null)
            {
                Regex extractor;
                extractor = new Regex(RegExp, RegexOptions.IgnoreCase | RegexOptions.Singleline);

                MatchCollection matches = extractor.Matches(e.Response.BodyString);
                if (matches.Count > 0)
                {
                    List<string> lstLables = new List<string>();
                    if (!string.IsNullOrEmpty(Labels))
                        lstLables = Labels.Split(';').ToList<string>();
                    else if (matches.Count > MatchIndexAsLabels - 1 && matches[MatchIndexAsLabels] != null)
                    {
                        foreach (Group item in matches[MatchIndexAsLabels].Groups)
                            lstLables.Add(item.Value);
                    }

                    if (lstLables.Count == matches[MatchIndexAsValues].Groups.Count)
                    {
                        foreach (Group item in matches[MatchIndexAsValues].Groups)
                        {
                            string name = (string.IsNullOrWhiteSpace(Preffix)) ? "nombre" : Preffix + ".nombre";
                            if (item.Value.Equals("&nbsp;") || string.IsNullOrWhiteSpace(item.Value))
                                e.WebTest.Context.Add(name, "");
                            else
                                e.WebTest.Context.Add(name, item.Value);
                        }
                    }
                }
                e.Success = true;
                return;

            }
            e.Success = false;
            e.Message = "Valores no pudieron ser extraidos";
        }

    }
}
